﻿using System;
using System.Collections.Generic;
using System.Drawing;

namespace SmallBasicFun.TicTacToeGame
{
	public class Board
	{
		private readonly Dictionary<Point, string> board = new Dictionary<Point, string>();
		private bool PlayerX = true;

		public string CurrentPlayer
		{
			get { return PlayerX ? "X" : "O"; }
		}

		public override string ToString()
		{
			string grid = StringUtils.DisplayGrid(3, 3, GetCell);
			//add the player who has won if there is a winner
			string player = GetWinner();

			if (IsGameWon(player))
			{
				grid += player + " has Won!!";
			}
			return grid;
		}


		public string GetCell(int x, int y)
		{
			if (board.ContainsKey(new Point(x, y)))
			{
				return board[new Point(x, y)];
			}
			return " ";
		}

		public string GetCurrentTurn()
		{
			return CurrentPlayer;
		}

		public bool IsValidPlay(int x, int y)
		{
			return IsValid(x, y);
		}

		public void PlacePiece(string mark, int x, int y)
		{
			Click(mark, x, y);
		}


		public void Click(string player, int x, int y)
		{
			board.Add(new Point(x, y), player);
			PlayerX = !PlayerX;
		}

		public bool IsGameWon(string s)
		{
			return GetWinner() == s;
		}

		public string GetWinner()
		{
			if (GetCell(0, 0) == GetCell(1, 1) && GetCell(0, 0) == GetCell(2, 2) && GetCell(0, 0) != " ")
			{
				return GetCell(0, 0);
			}

			if (GetCell(0, 2) == GetCell(1, 1) && GetCell(2, 0) == GetCell(0, 2) && GetCell(0, 2) != " ")
			{
				return GetCell(0, 2);
			}

			for (int y = 0; y < 3; y++)
			{
				if (GetCell(0, y) == GetCell(1, y) && GetCell(2, y) == GetCell(0, y) && GetCell(0, y) != " ")
				{
					return GetCell(0, y);
				}
			}

			for (int x = 0; x < 3; x++)
			{
				if (GetCell(x, 0) == GetCell(x, 1) && GetCell(x, 2) == GetCell(x, 0) && GetCell(x, 0) != " ")
				{
					return GetCell(x, 0);
				}
			}

			return board.Count == 9 ? "CAT" : null;
		}

		public bool IsValid(int x, int y)
		{
			if (x < 3 && y < 3 && x > -1 && y > -1)
			{
				return GetCell(x, y) == " ";
			}
			return false;
		}

		public int GetSquareByXY(int x, int y)
		{
			return x + (y - 1)*3;
		}

		public Point GetXYBySquare(int sqaure)
		{
			sqaure--;
			return new Point((sqaure%3), (sqaure/3));
		}

		public bool IsGameOver()
		{
			return GetWinner() != null;
		}

		public bool IsTieGame()
		{
			return GetWinner() == "CAT";
		}
	}
}